package com.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bean.AdminBean;

public class AdminLoginFilter implements Filter
{
	@Override
	public void init(FilterConfig filterConfig) throws ServletException
	{
	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException
	{
		HttpServletRequest hsp = (HttpServletRequest)request;
		String uri = hsp.getRequestURI();
		if(uri.endsWith("gif")  || uri.endsWith(".css")|| 
		   uri.endsWith(".png") || uri.endsWith("jpg")||
		   uri.endsWith(".js")  || uri.endsWith("login.jsp") ||
		   uri.endsWith("Login")|| uri.endsWith("loginError.jsp"))
		{
			chain.doFilter(request, response);
			return;
		}	
		
		//protect the session information , the session will lost in frameset or iframe
	
		HttpSession session = hsp.getSession();
		//protect the session data, session data will be lost in frameset or iframe
		((HttpServletResponse)response).addHeader("P3P", "CP=\"CAO PSA OUR\"");
		if(null == (AdminBean)session.getAttribute("admin"))
		{
   		    //the website is based on frameset label,so make whole window display login page
			response.getWriter().write("<script>top.location.href='/lab_admin/login.jsp'</script>");
			return;
		}
		else
		{
			chain.doFilter(request, response);
		}
	}
	@Override
	public void destroy()
	{
	}

}
